﻿using B.S.BasicData.Infrastructure;
using B.S.BasicData.Infrastructure.Implement;
using B.S.BasicData.Infrastructure.Interface;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Drawing.Imaging;
using System.Reflection;
using System.Text;

namespace B.S.BasicData.Api.Read
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection Addservices(this IServiceCollection services)
        {
            services.AddDbContext<MyDbContext>();
            
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            services.AddMediatR(x =>{x.RegisterServicesFromAssemblies(Assembly.GetEntryAssembly());}); 
            services.AddCors(x =>{x.AddPolicy("2211A", policy =>{policy.WithOrigins("http://localhost:5211").AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
                });
            });
           services.AddAutoMapper(typeof(MapperProFile));
            services.AddSwaggerGen(x =>
            {
                var file = AppContext.BaseDirectory + @"B.S.BasicData.Api.Read.xml";
                x.IncludeXmlComments(file, true);
            });

            return services;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="MyDbContext"></typeparam>
        /// <param name="services"></param>
        /// <param name="connextionString"></param>
        /// <param name="enableSqlLog">是否打印执行EF语句转义的sql</param>
        /// <returns></returns>
        public static IServiceCollection AddDbContext<MyDbContext>(this IServiceCollection services,string? connectionString, bool enableSqlLog) where MyDbContext : DbContext
        {
            return services.AddDbContext<MyDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                action.EnableRetryOnFailure(
                    maxRetryCount: 10,
                    maxRetryDelay: TimeSpan.FromSeconds(60),
                    errorNumbersToAdd: null);
                }).EnableSensitiveDataLogging();
                if (enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure.AddFilter((category, level) =>category==DbLoggerCategory.Database.Command.Name&&level==LogLevel.Information).AddConsole();
                       
                    }));
                }
            });
        }

        public static void AddJwt(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option =>
            {
                //取出私钥
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                option.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],
                    //验证接受者
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["Authentication:Audience"],
                    //验证是否过期
                    ValidateLifetime = true,
                    //验证私钥
                    IssuerSigningKey=new SymmetricSecurityKey(secretByte)
                };

            });
        }
    }
}
